import argparse
import logging
import os

import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from torchvision import transforms

from utils.data_loading import BasicDataset
from unet import UNet
from utils.utils import plot_img_and_mask

def predict_img(net,
                full_img,
                device,
                scale_factor=1,
                out_threshold=0.5):
    net.eval()
    img = torch.from_numpy(BasicDataset.preprocess(None, full_img, scale_factor, is_mask=False)) #将图片转换为张量
    img = img.unsqueeze(0) #    在第0维增加一个维度 1 3 640 959
    img = img.to(device=device, dtype=torch.float32)

    with torch.no_grad():
        output = net(img).cpu()#将输出转换为cpu
        output = F.interpolate(output, (full_img.size[1], full_img.size[0]), mode='bilinear') # 双线性插值 使得输出的大小和原图一样
        if net.n_classes > 1:
            mask = output.argmax(dim=1) #返回每一行中最大值的索引 就是对应每一个像素的类别
        else:
            mask = torch.sigmoid(output) > out_threshold

    return mask[0].long().squeeze().numpy()


def get_args():
    parser = argparse.ArgumentParser(description='Predict masks from input images')
    parser.add_argument('--model', '-m', default='unet_carvana_scale0.5_epoch2.pth', metavar='FILE',
                        help='Specify the file in which the model is stored')
    # parser.add_argument('--input', '-i', metavar='INPUT', nargs='+', help='Filenames of input images', required=True)#required=True表示必须要有输入文件
    parser.add_argument('--input', '-i', metavar='INPUT', nargs='+', default='data/imgs/0cdf5b5d0ce1_01.jpg',help='Filenames of input images')#nargs='+'表示至少有一个输入文件
    parser.add_argument('--output', '-o', metavar='OUTPUT', nargs='+',default='result.png' ,help='Filenames of output images')
    parser.add_argument('--viz', '-v', action='store_false',default=True,
                        help='Visualize the images as they are processed')
    parser.add_argument('--no-save', '-n', action='store_true', help='Do not save the output masks')
    parser.add_argument('--mask-threshold', '-t', type=float, default=0.5,
                        help='Minimum probability value to consider a mask pixel white')
    parser.add_argument('--scale', '-s', type=float, default=0.5,
                        help='Scale factor for the input images')
    parser.add_argument('--bilinear', action='store_true', default=False, help='Use bilinear upsampling')
    parser.add_argument('--classes', '-c', type=int, default=2, help='Number of classes')
    
    return parser.parse_args()


def get_output_filenames(args):
    def _generate_name(fn): #生成输出文件名
        return f'{os.path.splitext(fn)[0]}_OUT.png'

    return args.output or list(map(_generate_name, args.input)) # 如果没有指定输出文件名，那么就用输入文件名加上_OUT.png


def mask_to_image(mask: np.ndarray, mask_values): #将mask转换为图片
    if isinstance(mask_values[0], list): #如果mask_values是一个列表，那么就是多分类问题
        out = np.zeros((mask.shape[-2], mask.shape[-1], len(mask_values[0])), dtype=np.uint8)
    elif mask_values == [0, 1]:
        out = np.zeros((mask.shape[-2], mask.shape[-1]), dtype=bool)
    else:
        out = np.zeros((mask.shape[-2], mask.shape[-1]), dtype=np.uint8)

    if mask.ndim == 3:
        mask = np.argmax(mask, axis=0)

    for i, v in enumerate(mask_values):
        out[mask == i] = v #mask中的值为i的像素，out中的值就为v

    return Image.fromarray(out)


if __name__ == '__main__':
    args = get_args()
    logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')

    in_files = args.input
    out_files = get_output_filenames(args)

    net = UNet(n_channels=3, n_classes=args.classes, bilinear=args.bilinear)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    logging.info(f'Loading model {args.model}')
    logging.info(f'Using device {device}')

    net.to(device=device)
    state_dict = torch.load(args.model, map_location=device) #加载模型
    mask_values = state_dict.pop('mask_values', [0, 1]) #弹出mask_values 这个键值对，如果没有就返回[0,1]
    net.load_state_dict(state_dict)

    logging.info('Model loaded!')
    logging.info(f'Predicting image {in_files} ...')
    img = Image.open(in_files)

    mask = predict_img(net=net,
                        full_img=img,
                        scale_factor=args.scale,
                        out_threshold=args.mask_threshold,
                        device=device)

    if not args.no_save:
        out_filename = out_files
        result = mask_to_image(mask, mask_values)
        result.save(out_filename)
        logging.info(f'Mask saved to {out_filename}')

    if args.viz:
        logging.info(f'Visualizing results for image {in_files}, close to continue...')
        plot_img_and_mask(img, mask)

    # for i, filename in enumerate(in_files):
    #     logging.info(f'Predicting image {filename} ...')
    #     img = Image.open(filename)

    #     mask = predict_img(net=net,
    #                        full_img=img,
    #                        scale_factor=args.scale,
    #                        out_threshold=args.mask_threshold,
    #                        device=device)

    #     if not args.no_save:
    #         out_filename = out_files[i]
    #         result = mask_to_image(mask, mask_values)
    #         result.save(out_filename)
    #         logging.info(f'Mask saved to {out_filename}')

    #     if args.viz:
    #         logging.info(f'Visualizing results for image {filename}, close to continue...')
    #         plot_img_and_mask(img, mask)
